package problem3_LongestSubstringWithoutRepeatingCharacters;

import java.util.HashMap;
import java.util.Map;

public class Solution {
	public int lengthOfLongestSubstring(String s) {
		Map<Character,Integer> map=new HashMap<>();
		int max=0;
		for(int i=0,j=0;j<s.length();j++){
			if(map.containsKey(s.charAt(j))){
				i=Math.max(i, map.get(s.charAt(j)));  //abba
			}
			max = Math.max(max, j-i+1);
			map.put(s.charAt(j), j+1);
		}
		return max;
	}
	
	public int lengthOfLongestSubstring2(String s) {
        int n = s.length(), ans = 0;
       // int[26] for Letters 'a' - 'z' or 'A' - 'Z'
       // int[128] for ASCII
       // int[256] for Extended ASCII
        int[] index = new int[128]; // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            i = Math.max(index[s.charAt(j)], i);
            ans = Math.max(ans, j - i + 1);
            index[s.charAt(j)] = j + 1;
        }
        return ans;
    }
	
	public static void main(String[] args){
		Solution solution=new Solution();
		System.out.println(solution.lengthOfLongestSubstring2("abba"));
		System.out.println(solution.lengthOfLongestSubstring2("bbbbb"));
		System.out.println(solution.lengthOfLongestSubstring2("pwwkew"));
	}
}
